/**
 * 包裹管理工具模块
 * 用于管理快递包裹的本地数据存储
 */

const STORAGE_KEY = 'package_list'

/**
 * 获取包裹列表
 * @returns {Array} 包裹列表数组
 */
function getPackageList() {
  try {
    const data = uni.getStorageSync(STORAGE_KEY)
    if (data) {
      return JSON.parse(data)
    }
    return []
  } catch (error) {
    console.error('获取包裹列表失败:', error)
    return []
  }
}

/**
 * 保存包裹列表
 * @param {Array} list - 包裹列表
 */
function savePackageList(list) {
  try {
    uni.setStorageSync(STORAGE_KEY, JSON.stringify(list))
  } catch (error) {
    console.error('保存包裹列表失败:', error)
    throw error
  }
}

/**
 * 添加新包裹
 * @param {Object} newPackage - 新包裹对象 {pickupCode, expressCompany, location}
 * @returns {Object} 添加后的完整包裹对象
 */
function addPackage(newPackage) {
  try {
    const packageList = getPackageList()

    // 创建完整的包裹对象
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hour = String(now.getHours()).padStart(2, '0')
    const minute = String(now.getMinutes()).padStart(2, '0')
    const second = String(now.getSeconds()).padStart(2, '0')
    const createTime = `${year}-${month}-${day} ${hour}:${minute}:${second}`

    const packageData = {
      id: Date.now(), // 使用时间戳作为唯一ID
      pickupCode: newPackage.pickupCode,
      expressCompany: newPackage.expressCompany || '',
      location: newPackage.location,
      status: '待取', // 默认状态
      createTime: createTime
    }

    // 添加到列表开头（最新的在前面）
    packageList.unshift(packageData)

    // 保存到本地存储
    savePackageList(packageList)

    console.log('成功添加包裹:', packageData)
    return packageData
  } catch (error) {
    console.error('添加包裹失败:', error)
    throw error
  }
}

/**
 * 更新包裹状态
 * @param {Number} id - 包裹ID
 * @param {String} newStatus - 新状态（'待取' 或 '已取'）
 * @returns {Boolean} 是否更新成功
 */
function updatePackage(id, newStatus) {
  try {
    const packageList = getPackageList()
    const index = packageList.findIndex(pkg => pkg.id === id)

    if (index === -1) {
      console.error('未找到指定ID的包裹:', id)
      return false
    }

    // 更新状态
    packageList[index].status = newStatus
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hour = String(now.getHours()).padStart(2, '0')
    const minute = String(now.getMinutes()).padStart(2, '0')
    const second = String(now.getSeconds()).padStart(2, '0')
    packageList[index].updateTime = `${year}-${month}-${day} ${hour}:${minute}:${second}`

    // 保存到本地存储
    savePackageList(packageList)

    console.log('成功更新包裹状态:', packageList[index])
    return true
  } catch (error) {
    console.error('更新包裹失败:', error)
    throw error
  }
}

/**
 * 删除包裹
 * @param {Number} id - 包裹ID
 * @returns {Boolean} 是否删除成功
 */
function deletePackage(id) {
  try {
    const packageList = getPackageList()
    const newList = packageList.filter(pkg => pkg.id !== id)

    if (newList.length === packageList.length) {
      console.error('未找到指定ID的包裹:', id)
      return false
    }

    // 保存到本地存储
    savePackageList(newList)

    console.log('成功删除包裹, ID:', id)
    return true
  } catch (error) {
    console.error('删除包裹失败:', error)
    throw error
  }
}

/**
 * 获取待取包裹数量
 * @returns {Number} 待取包裹数量
 */
function getPendingCount() {
  try {
    const packageList = getPackageList()
    return packageList.filter(pkg => pkg.status === '待取').length
  } catch (error) {
    console.error('获取待取包裹数量失败:', error)
    return 0
  }
}

/**
 * 清空所有包裹
 * @returns {Boolean} 是否清空成功
 */
function clearAllPackages() {
  try {
    uni.removeStorageSync(STORAGE_KEY)
    console.log('成功清空所有包裹')
    return true
  } catch (error) {
    console.error('清空包裹失败:', error)
    throw error
  }
}

// 导出所有方法
export default {
  getPackageList,
  addPackage,
  updatePackage,
  deletePackage,
  getPendingCount,
  clearAllPackages
}
